<script setup>
import * as API  from '@/api/deal/log-deal-product-number.js'
import {reqCascaderData} from '@/api/deal/deal-product.js'
import {ref, reactive, onMounted} from 'vue'
import {getLocalTime} from "@/utils/time.js";
import {ElMessage} from "element-plus";
import {useRoute} from "vue-router";
import {reqNameList as reqProductTypeList} from "@/api/store/product.js";

// 用于表格
const pn = ref(1)
const ps = ref(10)
const total = ref(0)
const dealNumberList = ref([])


//用于搜索框
const searchOptions = reactive({
  dealProductId: null,
  multistageOptions: {
    storeId: null,
    clerkId: null,
    customerId: null,
  },
  productId: null,
  timeRange: [null, null],
})

// 处理清空时间框
const handleTimeRangeChange = (value) => {
  if (!value) {
    searchOptions.timeRange = [null, null]; // 确保在清空时，数组也完全重置
  }
}

const clearTimeRange = () => {
  searchOptions.timeRange = [null, null]; // 在用户手动清空时重置
}

// 级联选择器 搜索 | 表单项
const optionTreeValue = ref([])
const optionsTree = ref([])
const productTypeList = ref([])
const optionTreeHandler = (value)=>{
  if (!value || value.length === 0) {
    // 当级联选择器清空时，将 multistageOptions 的所有属性清空
    searchOptions.multistageOptions.storeId = null;
    searchOptions.multistageOptions.clerkId = null;
    searchOptions.multistageOptions.customerId = null;
  } else {
    // 正常处理级联选择器的选中值
    searchOptions.multistageOptions.storeId = value[0] || null;
    searchOptions.multistageOptions.clerkId = value[1] || null;
    searchOptions.multistageOptions.customerId = value[2] || null;
  }
}

//用于表单
const dialogFormVisible = ref(false)
const dealNumberParams = reactive({
  id: null,
  dealProductId: null,
  number: null,
  dealTime: null,
  notes: null,
})

const getPage = async (pager = 1)=>{
  pn.value = pager
  const result = await API.reqPage(
      pn.value,
      ps.value,
      searchOptions.dealProductId,
      searchOptions.multistageOptions.storeId,
      searchOptions.multistageOptions.clerkId,
      searchOptions.multistageOptions.customerId,
      searchOptions.productId,
      searchOptions.timeRange[0],
      searchOptions.timeRange[1]
  )
  if(result.code === "0"){
    total.value = result.data.total
    dealNumberList.value = result.data.items
  } else {
    ElMessage({type:"error", message:"获取数据失败！"})
  }
}

// const reqExport = async ()=>{
//   API.reqExport().then(resp => {
//     if (resp != null) {
//       ElMessage({
//         message: '导出成功',
//         type: 'success',
//       })
//       const link = document.createElement('a')
//       link.href = URL.createObjectURL(resp)
//       link.download = 'data.xlsx'
//       link.click()
//       URL.revokeObjectURL(link.href)
//     }
//   })
// }

const addDealNumber = ()=>{
  dialogFormVisible.value = true
  Object.assign(dealNumberParams,{
    id: null,
    dealProductId: searchOptions.dealProductId || null,
    number: null,
    dealTime: null,
    notes: null,
  })
}

const updateDealNumber = (row)=>{
  dialogFormVisible.value = true
  Object.assign(dealNumberParams,row)
}

const deleteDealNumber = async (id)=>{
  const result = await API.reqDelete(id)
  if (result.code === '0') {
    ElMessage({ type: 'success', message: '删除成功' })
    await getPage(dealNumberList.value.length > 1 ? pn.value : pn.value - 1);
  }
}

const cancel = ()=>{
  dialogFormVisible.value = false
}

const confirm = async ()=>{
  let result
  if(dealNumberParams.id){
    result = await API.reqUpdate(dealNumberParams)
  }else{
    result = await API.reqSave(dealNumberParams)
  }
  if (result.code === '0') {
    ElMessage({ type: 'success', message: dealNumberParams.id? '修改成功':'添加成功',})
    dialogFormVisible.value = false
    await getPage()
  } else {
    dialogFormVisible.value = false
    //提示消息
    ElMessage({ type: 'error', message: dealNumberParams.id ? '修改失败':'添加失败' });
  }
}

const search = async ()=>{
  await getPage()
}

onMounted(()=>{
  const $route = useRoute();
  // 获取 query 参数并赋值
  searchOptions.dealProductId = $route.query.dealProductId || null;
  //获取级联树
  reqCascaderData().then(resp => {
    optionsTree.value = resp.data.nameIdList
  })
  //获取商品类型列表
  reqProductTypeList().then(resp=>{
    productTypeList.value = resp.data.items
  })
  getPage()
})
</script>

<template>
  <!-- ----------------------------------- search ----------------------------------- -->
  <el-card>
    <el-scrollbar>
      <el-form class="search-card">
        <div class="search-input">
          <el-form-item>
            <el-input placeholder="请输入订单 ID" v-model="searchOptions.dealProductId" clearable></el-input>
          </el-form-item>
          <el-cascader
              placeholder="客户名"
              v-model="optionTreeValue"
              :options="optionsTree"
              @change="optionTreeHandler"
              expandTrigger="hover"
              :props="{ value: 'id', label: 'name', children: 'childrenList', checkStrictly: true, }"
              clearable
              filterable
          />
          <el-form-item>
            <el-select v-model="searchOptions.productId" clearable placeholder="货品名" style="width:180px">
              <el-option
                  v-for="item in productTypeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="时间">
            <el-date-picker
                v-model="searchOptions.timeRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD"
                @change="handleTimeRangeChange"
                @clear="clearTimeRange"
            />
          </el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" size="default" @click="search" >搜索</el-button>
        </el-form-item>
      </el-form>
    </el-scrollbar>
  </el-card>
  <!-- ----------------------------------- search ----------------------------------- -->

  <!-- ----------------------------------- table ----------------------------------- -->
  <el-card>
    <el-button type="primary" size="default" @click="addDealNumber">添加</el-button>
    <!-- <el-button type="primary" size="default" @click="reqExport">导出</el-button> -->

    <el-table  style="margin: 10px 0;" border :data="dealNumberList">
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column label="分店名" align="center" prop="storeName" show-overflow-tooltip></el-table-column>
      <el-table-column label="店员名" align="center" prop="clerkName" show-overflow-tooltip></el-table-column>
      <el-table-column label="客户名" align="center" prop="customerName" show-overflow-tooltip></el-table-column>
      <el-table-column label="货品名" align="center" prop="productName" show-overflow-tooltip></el-table-column>
      <el-table-column label="交易数量" align="center" prop="number" show-overflow-tooltip></el-table-column>
      <el-table-column label="交易时间" align="center" prop="dealTime" show-overflow-tooltip>
        <template #="{row}">
          <span>{{getLocalTime(row.dealTime, 1)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="notes" show-overflow-tooltip></el-table-column>
      <el-table-column label="创建/修改时间" align="center" prop="createTime" show-overflow-tooltip>
        <template #="{row}">
          <span>{{getLocalTime(row.createTime)}}</span>
          <br/>
          <span>{{getLocalTime(row.updateTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px" align="center">
        <template #="{row, $index}">
          <el-row>
            <el-col :span="12">
              <el-button type="primary" size="small" icon="Edit" @click="updateDealNumber(row)">编辑</el-button>
            </el-col>
            <el-col :span="12">
              <el-popconfirm :title="`确定要删除?`" width="260px" @confirm="deleteDealNumber(row.id)">
                <template #reference>
                  <el-button type="primary" size="small" icon="Delete">删除</el-button>
                </template>
              </el-popconfirm>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="getPage()"
        @current-change="getPage"
        v-model:current-page="pn"
        v-model:page-size="ps"
        :page-sizes="[10, 20, 50, 100]"
        :background="true"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
    />
  </el-card>
  <!-- ----------------------------------- table ----------------------------------- -->

  <!-- ----------------------------------- dialog ----------------------------------- -->
  <el-dialog
      v-model="dialogFormVisible"
      :title="dealNumberParams.id ? '修改订单记录' : '添加订单记录'"
  >
    <el-form style="width: 80%" :model="dealNumberParams">
      <el-form-item label="订单编号" label-width="100px">
        <el-input v-model="dealNumberParams.dealProductId"></el-input>
      </el-form-item>
      <el-form-item label="交易数量" label-width="100px">
        <el-input v-model="dealNumberParams.number"></el-input>
      </el-form-item>
      <el-form-item label="交易日期" label-width="100px">
        <el-date-picker
            v-model="dealNumberParams.dealTime"
            type="date"
            placeholder="交易日期"
        />
      </el-form-item>
      <el-form-item label="备注" label-width="100px">
        <el-input v-model="dealNumberParams.notes" type="textarea"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
      <el-button type="primary" size="default" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
  <!-- ----------------------------------- dialog ----------------------------------- -->
</template>

<style scoped lang="css">
.search-card {
  display: flex;
  align-items: center;
  flex-direction: row;
  flex-wrap: wrap;
  margin-bottom: 1rem;
  padding: 1rem;
  background-color: #f9f9f9;
  border-radius: 8px;
}
.search-input {
  display: flex;
  align-items: center;
  flex: 1 0 auto;
  gap: 1rem;
}
.search-input > * {
  flex: 0 1 auto;
}
.el-form-item {
  margin-bottom: 0;
  display: flex;
  align-items: center;
}
.el-form-item label {
  width: 80px; /* Adjust this value as needed */
}
.el-card {
  margin-bottom: 1rem;
}
.el-table {
  margin: 1rem 0;
}
.el-dialog {
  width: 50%;
}
.el-dialog .el-form-item {
  margin-bottom: 1rem;
}
.el-dialog .el-form-item p {
  margin-bottom: 0.5rem;
}
.el-dialog .el-form-item label {
  width: 120px; /* Adjusted width for better alignment */
}
.el-dialog .el-form-item .el-input,
.el-dialog .el-form-item .el-select,
.el-dialog .el-form-item .el-date-picker {
  width: calc(100% - 130px); /* Adjusted width to fit the label */
}
</style>